package com.atguigu.springcloud.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.concurrent.TimeUnit;

@Service
public class PaymentService {


    public String paymentInfo_OK(Integer id) {
        return "线程池：" + Thread.currentThread().getName() + "\t" + id;
    }


    //------------------------------------服务降级fallback

    //设置自身调用超时时间，峰值内可以运行，超过了需要有兜底方法，作为服务降级fallback
    //作为服务方，3秒以内成功，去调用正常的业务逻辑，3秒之后则掉超时
    @HystrixCommand(fallbackMethod = "paymentInfo_TimeoutHandler", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
    })
    public String paymentInfo_Timeout(Integer id) {

        int time = 2;

        //看看异常能不能fallback
        //结论：运行时异常和超时都能被fallback捕获
        int age = 10 / 0;
        try {
            TimeUnit.SECONDS.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "嘻嘻线程池成功了：" + Thread.currentThread().getName() + "\t" + id + "耗时" + time + "秒";
    }

    public String paymentInfo_TimeoutHandler(Integer id) {
        return "我是8001自己或者你出错了：" + Thread.currentThread().getName() + "\t" + id + "我是一个友好提示";
    }


    //---------------------------------------服务熔断


    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),  //是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"), //请求次数 至少有多少个请求才会开启错误百分比统计
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),  //时间窗口期  理解成休眠时间  经过多久后恢复一次尝试 half-open状态
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60")  //失败率达到多少
    })
    public String paymentCiruitBreker(@PathVariable("id") Integer id) {

        if (id < 0) {
            throw new RuntimeException("id不能为负数啊傻瓜");
        }
        String serialNumber = IdUtil.simpleUUID();
        return Thread.currentThread().getName() + "\t" + serialNumber;

    }

    public String paymentCircuitBreaker_fallback(@PathVariable("id") Integer id){
        return "id不能为负数哇，搞得我现在熔断了： "+id ;

    }


}
